﻿var allContact = null, currentContact;
function visitor() {
    if (currentLP.tqtype == 2) return;
    if (webconfig().line.visitorswitch == "0") return;
    $('#touristform').html('<h1><span>游客信息</span></h1>');
    for (var i in currentLP.crowd) {
        var o = currentLP.crowd[i], s = toInt($('#c' + o.id).val());
        for (var j = 1; j <= s; j++) {
            var tmp = '<div class="itemContent"><h3><span><label><em class="checkbox"><input type="checkbox" name="c' + o.id + '_save_' + j + '" value="1"></em>保存到常用联系人</label></span>第' + j + '位' + o.name + '</h3>';
            tmp += '<table class="formTable">';
            tmp += '<tr><td class="formTitle" width="100px;"><i>*</i>真实姓名：</td><td><div class="dropDown"><input type="text" name="c' + o.id + '_name_' + j + '" id="c' + o.id + '_name_' + j + '" class="formText">';
            tmp += '</div><span class="ins"><a href="javascript:void(0);" class="copyContact">[复制预订人姓名]</a></span><span id="box_c' + o.id + '_name_' + j + '"></span></td></tr>';
            tmp += '	<tr>';
            tmp += '		<td class="formTitle" width="100px;">性别：</td>';
            tmp += '		<td>';
            tmp += '			<label class="checkText"><input type="radio" class="checkbox" name="c' + o.id + '_sex_' + j + '" value="男" checked="checked">男</label>';
            tmp += '			<label class="checkText"><input type="radio" class="checkbox" name="c' + o.id + '_sex_' + j + '" value="女">女</label>';
            tmp += '		</td>';
            tmp += '	</tr>';
            tmp += '	<tr>';
            tmp += '		<td class="formTitle" width="100px;">手机号码：</td>';
            tmp += '		<td><input type="text" class="formText" id="c' + o.id + '_mobile_' + j + '" name="c' + o.id + '_mobile_' + j + '"></td>';
            tmp += '	</tr>';
            tmp += '	<tr>';
            tmp += '		<td class="formTitle" width="100px;"><i>*</i>证件号码：</td>';
            tmp += '		<td>';
            tmp += '			<select id="c' + o.id + '_cardtype_' + j + '" name="c' + o.id + '_cardtype_' + j + '" class="select">';
            tmp += '				<option selected="selected" value="身份证">身份证</option>';
            tmp += '				<option value="因私护照">因私护照</option>';
            tmp += '				<option value="港澳通行证">港澳通行证</option>';
            tmp += '				<option value="台胞证">台胞证</option>';
            tmp += '				<option value="军官证">军官证</option>';
            tmp += '				<option value="其它">其它</option>';
            tmp += '				<option value="出生日期">出生日期</option>';
            tmp += '			</select>';
            tmp += '			<input type="text" style="width:150px" class="formText" id="c' + o.id + '_card_' + j + '" name="c' + o.id + '_card_' + j + '">';
            tmp += '		</td>';
            tmp += '	</tr>';
            tmp += '</table></div>';
            $('#touristform').append(tmp);
            $('#c' + o.id + '_name_' + j).rules('add', { required: true, IsRealName: true });
            $('#c' + o.id + '_mobile_' + j).rules('add', { isMobile: true });
            $('#c' + o.id + '_card_' + j).rules('add', { required: function () { return currentLP.tqtype != 2; }, isIDCard: true });
            $('#c' + o.id + '_cardtype_' + j).change(function () {
                var id = $(this).attr('id').replace('_cardtype_', '_card_');
                $('#' + id).rules("remove", 'isIDCard');
                if ($(this).val() == '出生日期') {
                    $('#' + id).width(100).attr('readonly', true).addClass('inputDate').val('').datepicker({
                        maxDate: '0',
                        defaultDate: '+0',
                        changeYear: true,
                        changeMonth: true,
                        onClose: function (dateText, inst) {
                            $('#' + inst.id).valid();
                        }
                    });
                } else {
                    $('#' + id).width(150).attr('readonly', false).removeClass('inputDate').val('').datepicker("destroy");
                    if ($(this).val() == '身份证') {
                        $('#' + id).rules('add', { isIDCard: true });
                    }
                }
                $('#box_' + id).empty();
            });
        }
    }
    $('#touristform .copyContact').click(function () {
        $(this).parent().parent().find('input[id*="_name_"]').val($('#o_contact').val());
    });
}
//登录返回
function AlertLoginReturn(data) {
    location = location;
}
function attachmentnumber() {
    var s = 0
    $('#crowdlist input').each(function () {
        s += toInt($(this).val());
    });
    $('#Attachment select').each(function () {
        var min = toInt($(this).attr('m1')), max = toInt($(this).attr('m2')), f = $(this).attr('f'), n = toInt($(this).attr('n')), u = $(this).attr('u');
        if (min == -1) {
            min = s;
            max = (max > 0 ? max + s : s);
        } else if (max == 0) {
            max = s;
        }
        if (min > n) min = n;
        if (max > n) max = n;
        if (min > max) min = max;
        var tmp = '<option value="' + min + '">' + min + u + '</option>';
        if (min != max) {
            if (f == 0) {
                for (var i = min + 1; i < max; i++) {
                    tmp += '<option value="' + i + '">' + i + u + '</option>';
                }
            }
            tmp += '<option value="' + max + '">' + max + u + '</option>';
        }
        $(this).html(tmp).change(function () {
            feecount();
        });
    });
}
function loadusercard() {
    $.ajax({
        type: "get",
        url: webpath + 'sys/ajax/user/card.ashx',
        dataType: "xml",
        data: '',
        async: false,
        success: function (xml) {
            xml = $(xml);
            if (xml.find('err').length == 1) { alert(xml.find('err')); return; }
            xml.find('u').each(function () {
                appendCard($(this));
            });
        }
    });
}
//右则费用信息事件
function BillinginfoEvent() {
    var BillinginfoTop = $('.detailedList').parent().offset().top;
    $(window).scroll(function () {
        var s = $(this).scrollTop() - BillinginfoTop + 1;
        if (s < 0) s = 0;
        $('.detailedList').stop().animate({ top: s }, 'fast');
    });
}
//格式化上车地点
function formatDeparture(pid) {
    var uls = $('#departure_' + pid + '>ul');
    var table = $('#geton table');
    table.find('tr:gt(0)').remove();
    if (uls.length > 0) {
        $('#geton').show();
        uls.each(function () {
            var getonaddr = $(this).find('.addr').text();
            table.append('<tr><td><input type="radio" checked="checked" value="[' + $(this).find('.date').text() + ']' + getonaddr + '" name="o_geton"></td><td>' + $(this).find('.date').text() + '</td><td>' + getonaddr + '</td><td>' + $(this).find('.return').text() + '</td><td>' + $(this).find('.text').text() + '</td><td>' + $(this).find('.flag').text() + '</td></tr>');
        });
        table.find(':radio').first().prop('checked', true);
    }
    else {
        $('#geton').hide();
    }
}
//插入卡
function appendCard(u, p, b) {
    var t = u.attr('type'), tmp, cardid = u.attr('id');
    tmp = '<tr><td><div class="info">' + (t == '0' ? '礼券' : (t == '1' ? '购物卡' : '代金券')) + '</div></td>';
    tmp += '<td><em class="card">' + u.attr('number') + '</em></td>';
    if (t == '0') {
        tmp += '<td>余额只能一次性使用</td>';
    } else if (t == '1') {
        tmp += '<td>余额可多次使用</td>';
    }
    tmp += '<td><em class="price">&yen;' + u.attr('balance') + '</em></td>';
    tmp += '<td><input type="text" name="card_' + cardid + '" id="card_' + cardid + '" balance=' + u.attr('balance') + ' tmp="' + u.attr('type') + '" class="formText" style="width:50px" value="' + (t == '1' ? u.attr('balance') : 0) + '"/>';
    if (!!p) tmp += '<input type="hidden" name="pass_' + cardid + '" value="' + p + '" /><input type="hidden" name="binding_' + cardid + '" value="' + b + '" />';
    tmp += '</td></tr>';
    if (t == '2') {
        $('#xjcard  tr:last').after(tmp);
    } else {
        $('#dyorcard tr:last').after(tmp);
    }
    $('#card_' + cardid).inputOnlyNum(); //只能输入数字
    $('#card_' + cardid).inputDefault('0', '', '', function (t) {
        var p = toInt($(t).attr('balance'));
        if (toInt($(t).val()) > p) $(t).val(p);
        feecount();
    }).blur();
}
//插入营销策略
function formatPromotion() {
    if (webconfig().promotionreckon == '2') {//互斥切换
        $('#Promotion').before('<div class="options clearfix"><span><em class="checkbox"><input name="yhxx" id="yxcl" type="radio" value="2" checked="checked" />使用活动优惠</em></span><span><em class="checkbox"><input name="yhxx" id="sydy" type="radio" value="1" />奖金或卡券</em></span></div>');
        $('#yxcl,#sydy').click(function () {
            $('#Promotion').parent().children().hide();
            $('.options').show();
            if ($(this).attr('id') == 'yxcl') {
                $('#sydy').prop('checked', false);
                $('#Promotion').show();
            } else {
                $('#yxcl').prop('checked', false);
                if (GetCookie('username') != '') {
                    $('#dyorcard').show();
                    $('#dyorcard').prev('h2').show();
                }
            }
            if (GetCookie('username') != '') {
                $('#xjcard,#cardform').show();
                $('#xjcard').prev('h2').show();
            } else {
                $('#loginfrom').show();
            }
            feecount();
        });
    } else {
        if (webconfig().promotionreckon == '0') $('#Promotion').insertAfter('#dyorcard'); //先计算积分,把营销策略插入在积分之后
        //$('#dyorcard').insertAfter('#Promotion'); //插入在积分之前
        $('#Promotion').before('<h2 class="h2Title">优惠活动</h2>');
        $('#dyorcard').before('<h2 class="h2Title">奖金或卡券</h2>');
        if (GetCookie('username') == '') {
            $('#Promotion').parent().children().hide();
            $('#Promotion').show();
            $('#Promotion').prev('h2').show();
            $('#loginfrom').show();
        }
    }
    //添加卡事件
    $('#a_card').blur(function () {
        var v = $.trim($(this).val());
        if (v == '') {
            $('#a_pass').parent().parent().hide();
            $('#a_pass').parent().parent().prev().hide();
            return;
        }
        $.get(webpath + 'sys/ajax/user/card.ashx', { card: v },
			function (xml) {
			    xml = $(xml);
			    if (xml.find('err').length == 1) {
			        var errstr = xml.find('err').text();
			        if (errstr == '卡号或密码错误') {
			            $('#a_pass').parent().parent().show();
			            $('#a_pass').parent().parent().prev().show();
			        } else {
			            alert(xml.find('err').text()); return;
			        }
			    }
			},
			'xml'
		);
    });
    $('#addcard').click(function () {
        var c = $.trim($('#a_card').val()), p = $('#a_pass').val(), b = $('#a_binding:checked').length;
        if (c == '') { alert('请添加卡号'); return; }
        $.get(webpath + 'sys/ajax/user/card.ashx', { card: c, pass: p, binding: b },
			function (xml) {
			    xml = $(xml);
			    if (xml.find('err').length == 1) { alert(xml.find('err').text()); return; }
			    $('#a_card').val('');
				$('#a_pass').parent().parent().hide();
				$('#a_pass').parent().parent().prev().hide();

			    var u = xml.find('u');
			    if ($('#card_' + u.attr('id')).length == 1) {
			        alert('此卡已添加,请不要重复添加.');
			        return;
			    }
			    appendCard(u, p, b);
			},
			'xml'
		);
    });
}
//发票事件
function invoiceEvent() {
    $('#needinvoice1').click(function () {
        $('#lo_invoice').parent().parent().show();
        $('#o_invoicetext').parent().parent().show();
    });
    $('#needinvoice0').click(function () {
        $('#box_o_invoice').empty();
        $('#lo_invoice').parent().parent().hide();
        $('#o_invoicetext').parent().parent().hide();
    }).click();
}
// 联系方式验证
$(function () {
    vip.viewPrice = 1; //日历里是否显示会员价
    if (GetCookie('username') != '') {
        loadusercard();
        $('#loginfrom').remove();
        vip.id = toInt(webconfig().user.rankid);
        vip.name = webconfig().user.rankname;
    }
    $('#o_contact').blur(function () {
        formatContract();
    });
    $.validator.addMethod("numberOfPeople", function (value) {
        var s = 0;
        $('#crowdlist input').each(function () {
            s += toInt($(this).val());
        });
        return s > 0;
    }, '请填写出游人数!');
    BillinginfoEvent(); //右则费用信息事件
    formatPromotion(); //插入营销策略和绑定卡券事件
    $('#srjj').html('&yen;' + $('#userbonus').val()); //用户积分

    $('#o_diyong').inputOnlyNum(); //只能输入数字
    $('#o_diyong').inputDefault('0', '', '', function (t) {
        var p = toInt($('#userbonus').val()), s = toInt($('#kyjj').text().replace('元', '')), tv = toInt($(t).val());
        if (tv > p) tv = p;
        if (tv > s) tv = s;
        $(t).val(tv);
        feecount();
    }).val(0);
    $('#o_feescount1').inputOnlyNum();
    $('#o_feescount1').inputDefault('0');
    $('#nexts,#next').click(function () { //下一步
        var isValid = true;
        $('#fillOrder').find(':input').each(function (i, item) {
            if (!$(item).valid())
                isValid = false;
        });
        if (isValid) {
            $('#fillOrder').hide();
            $('#fillTraveler').show();
            visitor();
        }
    });
    $('#returns').click(function () { //上一步 
        $('#touristform input').each(function () {
            $(this).rules('remove');
        });
        $('#touristform').empty();
        $('#fillTraveler').hide();
        $('#fillOrder').show();
    });

    $('#touristform').on('focus', 'input[name*="_name_"]', function () {
        var pUid = $('#userid').val();
        if (pUid == 0)
            return;
        var domId = $(this).attr("id");

        $('[name*="menu_o_comenames_"]').hide();
        if ($('#menu_' + domId).length > 0) {
            $('#menu_' + domId).show();
            return;
        }
        var a = $(this).offset();
        $(this).after('<div id="menu_' + domId + '"  name="menu_' + domId + '" class="commonly"></div>');
        $('#menu_' + domId).css({ 'position': 'absolute', 'z-index': 9999, 'background-color': 'White' }).offset({ top: a.top + 28, left: a.left });
        $.get(webpath + 'sys/ajax/user/Contact.ashx?uid=' + pUid, { t: Math.random() }, function (json) {
            if (json.length < 1)
                return;
            tempUserGC = json;
            var t = '<div style=" height:26px; line-height:26px; padding:0 10px; color:#FFF;background:#FB9125;">常用联系人<a style="float:right; color:#FFF;" href="javascript:void(0);" onclick="$(\'#menu_' + domId + '\').hide();">关闭</a></div>';
            var t2 = '<table width="250" border="0" cellspacing="0" cellpadding="0" style="border: 1px solid #CCCCCC; border-top:none;"><tr style="background:#F5F5F5;"><td style="padding-left:5px;">姓名</td><td>性别</td><td>手机</td></tr>';
            for (var i = 0; i < json.length; i++) {
                t2 += '<tr style="cursor:pointer;" onmouseover="this.style.background=\'#FAFAFA\'" onmouseout="this.style.background=\'#FFFFFF\'"  onclick="LoadUserContact(' + json[i].UC_ID + ',\'' + domId + '\')" ><td style="padding-left:5px;">';
                t2 += '<a href="javascript:void(0);">' + json[i].UC_RealName + '</a></td>';
                t2 += '<td>' + json[i].UC_Sex + '</td><td>' + json[i].UC_Mobile + '</td></tr>';
            }
            t2 += "</table>";
            $('#menu_' + domId).html(t + t2);
        });
    });
    //表单验证
    $("#TourExForm").validate({
        rules: {
            o_startdate: { required: true },
            o_contact: { required: true, IsRealName: true },
            o_mobile: { required: function () { return $.trim($('#o_mobile').val()) == '' && $.trim($('#o_email').val()) == '' }, isMobile: true },
            o_email: { required: function () { return $.trim($('#o_email').val()) == '' && $.trim($('#o_mobile').val()) == '' }, email: true },
            o_text: { maxlength: 200 },
            lo_invoice: { required: function () { return $('#needinvoice1').prop('checked') } },
            Proof: { required: true, remote: { url: webpath + 'Sys/ajax/CheckProof.ashx', type: 'get', dataType: 'json', data: { 'checktext': function () { return $('#Proof').val(); } }, cache: false} },
            Agreement: { required: true }
        },
        messages: {
            o_startdate: { required: '请选择出发日期' },
            o_mobile: { required: '手机和邮箱必须选填一项!' },
            o_email: { required: '手机和邮箱必须选填一项!' },
            lo_invoice: { required: '请填写发票抬头!' },
            Proof: { required: '请填写验证码', remote: function () { get_Code(webpath, 'TourExForm'); return '验证码错误!' } }
        },
        Agreement: { required: '请同意合同协议' }, submitHandler: function (form) {
            var s = 0;
            $('#crowdlist input').each(function () {
                s += toInt($(this).val());
            });
            if (s < 1) { alert('请填写出游人数'); return false; }
            if (currentLP.tqtype == 2) {
                $('#touristform').empty();
            }
            if (!$('#needinvoice').prop('checked')) {
                //$('#lo_invoice,#invoicetext').val('');
            }
            //清理出使用的卡卷
            var t = '';
            $('#dyorcard input[name^="card_"],#xjcard input[name^="card_"]').each(function () {
                if (toInt($(this).val()) > 0) {
                    t += ',' + $(this).attr('id').replace('card_', '')
                }
            });
            if (t != '') {
                $("#TourExForm").append('<input type="hidden" name="o_card" value="' + t + '" />')
            }
            ShowWindow('', 'submit-tip');
            form.submit();
        }
    });



    invoiceEvent(); //发票事件
    //保险事件
    $('#insuranceform [name="o_insurance"]').click(function () {
        feecount();
    });
    $('#insuranceform .info').hover(function () {
        $(this).find('.moreBox').show();
    }, function () {
        $(this).find('.moreBox').hide();
    });
    if (webconfig().line.bookingproof == 0) {
        $('#Proof').parent().parent().hide();
        $('#Proof').rules('remove');
    }

    $('#pricetype>ul').each(function () {
        var pid = $(this).attr('p_id');
        LP['p_' + pid] = { name: $(this).attr('p_name'), crowd: [], date: null, tqtype: $(this).attr('tqtype'), min: toInt($(this).attr('minadvance')), max: toInt($(this).attr('maxadvance')) };
        $('#pricetyperadio').append('<label class="checkText"><input type="radio" value="' + pid + '" name="o_pricetype" class="checkbox">' + $(this).attr('p_name') + '</label>');
        $(this).children('li').each(function () {
            LP['p_' + pid].crowd['i' + $(this).attr('crowdid')] = { id: $(this).attr('crowdid'), name: $(this).text(), bonus: $(this).attr('bonus'), diyong: $(this).attr('diyong') };
        });
    });
    $('#pricetyperadio :radio').click(function () {
        var p_id = $(this).val(), obj;
        formatDeparture(p_id); //格式化上车地点
        $("#o_startdate").datepicker("destroy");
        $('#o_startdate').unbind('click');
        obj = $('#crowdlist input:first');
        if (obj.length == 1) obj.rules('remove');
        $('#crowdlist').empty();
        currentLP = LP['p_' + p_id];
        if (currentLP.tqtype == 2) {
            $('#Budget').show();
            $('#noytyj,#touristform,#Billinginfo,#Billinginfos').hide();
            $('#o_startdate').datepicker({
                minDate: (new Date(Date.parse(webconfig().date.replace(/-/g, '/')))).DateAdd('d', currentLP.min),
                maxDate: (new Date(Date.parse(webconfig().date.replace(/-/g, '/')))).DateAdd('d', currentLP.max),
                changeYear: true,
                changeMonth: true
            });
            $('#o_feescount1').rules('add', { required: true, min: 1, messages: { required: '请填写预算费用', min: '请填写预算费用'} });


            //更新价格列表
            var tmp = '<tr><th>名称</th><th width="17%">数量</th></tr>';
            for (var i in currentLP.crowd) {
                var v = currentLP.crowd[i];
                tmp += '<tr><td>' + v.name + ':</td><td><a href="javascript:void(0);" class="plus"></a><input id="c' + v.id + '" name="c' + v.id + '" type="text" value="0" class="inputQuantity" maxlength="2" /><a href="javascript:void(0);" class="minus"></a></td></tr>';
            }
            $('#crowdlist').html(tmp);
            //出游人数更换
            var o = $('#crowdlist input');
            o.inputOnlyNum(); //只能输入数字
            o.inputDefault('0');
            o.blur(function () {
                var t = $(this).val();
                if (t == '' || t == 0) { $(this).val(0); return; };
                t = toInt(t);
                if (t > 99) $(this).val(m);
            });
            obj = $('#crowdlist');
            obj.find('.plus').click(function () {//减少
                var o = $(this).next(), v = o.val();
                if (v == '' || toInt(v) < 1) { o.val(0); return false; }
                o.val(toInt(v) - 1);
            });
            obj.find('.minus').click(function () {//增加
                var o = $(this).prev(), v = o.val();
                if (v == '') v = 0;
                v = toInt(v);
                if (++v > 99) v = 99;
                o.val(v);
            });
            obj = $('#crowdlist input:first');
            $('#crowdlist').append('<tr><td colspan="2"><div id="bxmsg">注：独立成团价格一团一议，需根据您的实际出游情况进行报价</div><div id="box_' + obj.attr('id') + '"></div></tr>');
            obj.rules('add', 'numberOfPeople');
            return;
        }
        $('#Budget').hide();
        $('#noytyj,#touristform,#Billinginfo,#Billinginfos').show();
        $('#o_feescount1').rules("remove");
        $('#o_startdate').click(function () {
            $('#calendarcontainer').show(200);
            $('#calendarcontainer').unclickOther();
            $('#calendarcontainer').clickOther('o_startdate', function () { $('#calendarcontainer').hide(); });
        });
        //获取价格
        if (currentLP.date == null) {
            currentLP.date = $.ajax({ url: webpath + 'sys/ajax/line/DatePrice.ashx', data: 'a=1&priceid=' + p_id, async: false }).responseXML;
            for (var i in currentLP.crowd) {
                $(currentLP.date).find('c[crowdid="' + currentLP.crowd[i].id + '"]').attr('name', currentLP.crowd[i].name);
            }
            LC['calendarcontainer'] = ['', '', '', $(currentLP.date).children('root').children('d'), '', '', 0, function (t) {
                var d = $(t).attr('id');
                $('#o_startdate').val(d);
                var obj = $(currentLP.date).find('d[date="' + d + '"]'), numbercount = toInt(obj.attr('number'));
                obj.children('c').each(function () {
                    var price = toInt($(this).attr("price"));
                    var crowdid = $(this).attr('crowdid');
                    $('#c' + crowdid).attr('disabled', false);
                    if (obj.attr('deluserprice') == '0') {
                        var u = $(this).children('u[rankid="' + vip.id + '"]');
                        if (u.length > 0) price = toInt(u.attr('userprice'));
                    }
                    price = price == -1 ? '电询' : '&yen;' + price;
                    $('#c' + crowdid + '_price').html(price);
                    $('#c' + crowdid).val(0);
                    if (price == '电询') {
                        $('#c' + crowdid).parent().contents().hide();
                        $('#c' + crowdid + '_number').empty();
                        $('#c' + crowdid + '_sd').hide();
                    } else {
                        $('#c' + crowdid + '_sd').show();
                        $('#c' + crowdid).parent().contents().show();
                        if (numbercount < 1) {
                            $('#c' + crowdid + '_number').html(0);
                            $('#c' + crowdid).val(0).attr('disabled', true).siblings('em').hide();
                        } else {
                            $('#c' + crowdid).val($('#pricetype>ul[p_id="' + $('#pricetyperadio :radio:checked').val() + '"] li[crowdid="' + crowdid + '"]').attr('c'));
                        }
                    }
                });
                $('#calendarcontainer').hide();
                obj = $('#crowdlist input');
                obj.filter(function () { return $(this).val() != '0'; }).each(function () {
                    $(this).blur();
                });
                attachmentnumber();
                feecount();
            } ];
        } else {
            LC['calendarcontainer'][3] = $(currentLP.date).children('root').children('d');
        }
        //更换附加产品Attachment
        obj = $(currentLP.date).find('a');
        var tmp1 = '';
        for (var i = 0; i < obj.length; i++) {
            tmpobj = $(obj[i]), t = tmpobj.attr('type');
            tmp = (i == 0 ? '' : $(obj[i - 1]).attr('type'));
            if (tmp != t) {
                tmp1 += '<h1><span>' + t + '</span></h1>';
                tmp1 += '		<div class="contentBox"><table class="formTable tableStyle2">';
                tmp1 += '			<tr>';
                tmp1 += '				<th style="text-align:left;padding-left:3px;">名称</th>';
                tmp1 += '				<th width="10%">价格</th>';
                tmp1 += '				<th width="10%">购买数量</th>';
                tmp1 += '			</tr>';
            }
            tmp1 += '<tr>';
            tmp1 += '	<td><div class="info"><a class="name down" href="javascript:void(0);">' + tmpobj.attr('name') + '</a><div class="moreBox"><div class="more"><b class="arrow">&nbsp;</b>' + tmpobj.text() + '</div></div></div></td>';
            tmp1 += '	<td><em class="price">' + (tmpobj.attr('price').indexOf('-') == 0 ? '-&yen;' + tmpobj.attr('price').substring(1) : '&yen;' + tmpobj.attr('price')) + '</em></td>';
            tmp1 += '	<td><select u="' + tmpobj.attr('units') + '" p="' + tmpobj.attr('price') + '" m1="' + tmpobj.attr('min') + '" m2="' + tmpobj.attr('max') + '" n="' + tmpobj.attr('number') + '" f="' + tmpobj.attr('fixed') + '" id="o_attachmentnumber_' + tmpobj.attr('id') + '" name="o_attachmentnumber_' + tmpobj.attr('id') + '" class="select"></select></td>';
            tmp1 += '</tr>';
            tmp = (i + 1 == obj.length ? '' : $(obj[i + 1]).attr('type'));
            if (tmp != t) {
                tmp1 += '		</table></div>';
            }
        }
        if (tmp1 != '') {
            $('#Attachment').html(tmp1).show();
            $('#Attachment .info').hover(function () {
                $(this).find('.moreBox').show();
            }, function () {
                $(this).find('.moreBox').hide();
            });
        } else {
            $('#Attachment').empty().hide();
        }

        //初始化日历
        tmp = $('#o_startdate').val();
        obj = $(LC['calendarcontainer'][3]).filter('d[date="' + tmp + '"]');
        if (tmp != '' && obj.length == 1) {
            tmp = new Date(Date.parse(tmp.replace(/-/g, '/')));
            CalendarPage('calendarcontainer', tmp.getFullYear(), tmp.getMonth() + 1);
        } else {
            CalendarPage('calendarcontainer', 0, 0);
        }

        //更换营销策略
        var tmp = '';
        $(currentLP.date).find('p').each(function () {
            var obj = $(this);
            tmp += '<tr>';
            tmp += '	<td><em class="checkbox"><input type="checkbox" name="O_PromotionID" value="' + obj.attr('id') + '" ruletype="' + obj.attr('ruletype') + '" discounttype="' + obj.attr('discounttype') + '" discountvalue="' + obj.attr('discountvalue') + '" minimum="' + obj.attr('minimum') + '" circle="' + obj.attr('circle') + '" cardcount="' + obj.attr('cardcount') + '"></em></td>';
            tmp += '<td>' + obj.text();
            if (toInt(obj.attr('ruletype')) > 2) tmp += ' [<a href="javascript:void(0);" title="送完即止">余:' + obj.attr('cardcount') + '张</a>]';
            tmp += '	</td>';
            tmp += '	<td><em>' + obj.attr('minimum') + '</em>' + (obj.attr('ruletype') == 0 || obj.attr('ruletype') == 3 ? '人' : '元') + '</td>';
            tmp += '	<td>';
            switch (obj.attr('ruletype')) {
                case '0':
                    if (obj.attr('discounttype') == '0') {
                        tmp += ' [直减]' + obj.attr('discountvalue') + '%';
                    } else {
                        tmp += ' [直减]' + obj.attr('discountvalue') + '元' + (obj.attr('circle') == '1' ? '*(人数/' + obj.attr('minimum') + ')' : '');
                    }
                    break;
                case '1':
                    if (obj.attr('discounttype') == '0') {
                        tmp += ' [直减]' + obj.attr('discountvalue') + '%';
                    } else {
                        tmp += ' [直减]' + obj.attr('discountvalue') + '元' + (obj.attr('circle') == '1' ? '*(总费用/' + obj.attr('minimum') + ')' : '');
                    }
                    break;
                case '2':
                    if (obj.attr('discounttype') == '0') {
                        tmp += ' [直减]' + obj.attr('discountvalue') + '%';
                    } else {
                        tmp += ' [直减]' + obj.attr('discountvalue') + '元' + (obj.attr('circle') == '1' ? '*(总费用/' + obj.attr('minimum') + ')' : '');
                    }
                    break;
                case '3':
                    tmp += ' [送卡]' + '1张' + (obj.attr('circle') == '1' ? '*(人数/' + obj.attr('minimum') + ')' : '');
                    break;
                default:
                    tmp += ' [送卡]' + '1张' + (obj.attr('circle') == '1' ? '*(总费用/' + obj.attr('minimum') + ')' : '');
                    break;
            }
            tmp += '	</td>';
            tmp += '</tr>';
        });
        if (tmp != '') {
            $('#Promotion tr:gt(0)').remove();
            $('#Promotion').append(tmp).show().find('[name="O_PromotionID"]').click(function () {
                if ($(this).prop('checked')) {
                    $('#Promotion [name="O_PromotionID"]').prop('checked', false);
                    $(this).prop('checked', true);
                }
                feecount();
            }).first().click();
            $('#Promotion').prev().show();
            if (webconfig().promotionreckon == '2') $('#yxcl').click();
        } else {
            $('#Promotion').empty().hide();
            $('#Promotion').prev().hide();
            $('#sydy').click();
            $('.options').hide();
            $('#yhinfotitle').text('卡卷、' + webconfig().bonusname);
        }
        //更新价格列表
        tmp = '<tr><th>名称</th><th width="10%">单价</th><th width="17%">数量</th><th width="10%">金额</th><th width="22%" name="dytd"> 抵送 </th></tr>';
        var ydy = 1;
        for (var i in currentLP.crowd) {
            var v = currentLP.crowd[i];
            tmp += '<tr><td>' + v.name + '</td>';
            tmp += '<td><em class="price" id="c' + v.id + '_price"></em></td>';
            tmp += '<td><a href="javascript:void(0);" class="plus"></a><input id="c' + v.id + '" name="c' + v.id + '" type="text" value="0" class="inputQuantity" maxlength="2" /><a href="javascript:void(0);" class="minus"></a></td>';
            tmp += '<td><em class="price" id="c' + v.id + '_count"></em></td>';
            tmp += '<td name="dytd"><ul id="c' + v.id + '_sd" class="promotions">';
            if (v.bonus > 0) {
                tmp += '<li class="send">送<span>&yen;' + v.bonus + '</span></li>';
                ydy = 0;
            }
            if (v.diyong > 0) {
                tmp += '<li>抵<span>&yen;' + v.diyong + '</span></li>';
                ydy = 0;
            }
            tmp += '</ul></td></tr>';
        }
        $('#crowdlist').html(tmp);
        if (ydy == 1) {
            $('#crowdlist [name="dytd"]').remove();
        }
        obj = $('#crowdlist input:first');
        $('#crowdlist').append('<tr><td colspan="' + (5 - ydy) + '"><div id="bxmsg"></div><div id="box_' + obj.attr('id') + '"></div></tr>');
        obj.rules('add', 'numberOfPeople');
        obj = $('#crowdlist');
        //出游人数更换
        obj.find('input').inputOnlyNum(); //只能输入数字
        obj.find('input').blur(function () {
            if ($(this).prop('disabled')) {
                $(this).val(0); return;
            }
            var t = toInt($(this).val()), c = $(this).attr('id').replace('c', '');
            if (t != 0) {
                var m = surplus(c);
                if (t > m) t = m;
                if (t < 0) t = 0;
                $(this).val(t);
            }
            attachmentnumber();
            feecount();
            $('#pricetype>ul[p_id="' + $('#pricetyperadio :radio:checked').val() + '"] li[crowdid="' + c + '"]').attr('c', $(this).val());
        });
        obj.parent().find('.plus').click(function () {//减少
            var o = $(this).next(), v = toInt(o.val()) - 1;
            o.val(v).blur();
        });
        obj.parent().find('.minus').click(function () {//增加
            var o = $(this).prev(), v = toInt(o.val()) + 1;
            o.val(v).blur();
        });
        obj = $('#calendarcontainer #' + $('#o_startdate').val() + '[v="1"]');
        if (obj.length == 0) {
            obj = $('#calendarcontainer td[v="1"]:first');
        }
        obj.click();
    });
    $('#pricetyperadio [name="o_pricetype"][value="' + $('#pricetypeid').val() + '"]').prop('checked', true).click();
    feecount();
});
var ContractHtml=null;
function formatContract() {
    if (ContractHtml == null) ContractHtml = $('#contract').html();
    var tmp = ContractHtml, D = (new Date(Date.parse($("#o_startdate").val()))), firtParty = $("#o_contact").val();
    tmp = tmp.replace(/{甲方}/g, webconfig().sitename).replace(/{日期}/g, D.getFullYear() + '年' + (D.getMonth() + 1) + '月' + D.getDate() + '日');
    if (firtParty.length > 0) {
        tmp = tmp.replace(/{乙方}/g, firtParty);
    }
    $('#contract').html(tmp);
}
function surplus(c) {
    var l = currentLP, x = $(l.date);
    x = x.find('root>d[date="' + $('#o_startdate').val() + '"]');
    var numbercount = toInt(x.attr('number'));
    for (var i in l.crowd) {
        if (l.crowd[i].id != c) {
            numbercount -= toInt($('#c' + l.crowd[i].id).val());
        }
    }
    return numbercount;
}
function feecount() {
    formatContract();
    if ($('#Budget').is(':visible')) return;
    var startdate = $('#o_startdate').val();
    var tmp = '', tmp1 = '', s, price, c;
    var count = [0, 0, 0, 0], obj = $(currentLP.date).find('d[date="' + startdate + '"]');
    //count 0.费用总计 1.奖金总计 2.可使用奖金 3.人数
    obj.children('c').each(function () {
        var price = toInt($(this).attr("price"));
        if (price < 0) return;
        var crowdid = $(this).attr('crowdid');
        if (obj.attr('deluserprice') == '0') {
            var u = $(this).children('u[rankid="' + vip.id + '"]');
            if (u.length > 0) price = toInt(u.attr('userprice'));
        }
        s = toInt($('#c' + crowdid).val());
        count[3] += s;
        count[0] += price * s;
        count[1] += currentLP.crowd['i' + crowdid].bonus * s;
        count[2] += currentLP.crowd['i' + crowdid].diyong * s;
        $('#c' + crowdid + '_count').html('&yen;' + (price * s));
        if (s > 0) tmp1 += '<dd>' + s + currentLP.crowd['i' + crowdid].name + '×&yen;' + price + '<em class="price">&yen;' + (price * s) + '</em></dd>	';

    });
    if (tmp1 != '') {
        tmp += '<dl><dt>出游团费</dt>' + tmp1 + '</dl>';
        tmp1 = '';
    }
    $('#insuranceform [name="o_insurance"]:checked').each(function () {
        price = toInt($('#insuranceprice_' + $(this).val()).attr('v'));
        s = price * count[3];
        count[0] += s;
        if (s > 0) tmp1 += '<dd class="title">' + $(this).parent().parent().find('a:first').text() + '</dd><dd>' + count[3] + '份×&yen;' + price + '<em class="price">&yen;' + s + '</em></dd>';
    });
    if (tmp1 != '') {
        tmp += '<dl><dt>保险费用</dt>' + tmp1 + '</dl>';
    }
    tmp1 = '';
    //附加产品
    obj = $(currentLP.date).find('a');
    $('#Attachment select').each(function () {
        price = toInt($(this).attr('p')); s = toInt($(this).val());
        c = price * s;
        count[0] += c;
        if (s > 0) {
            var o = obj.filter('[id="' + $(this).attr('id').replace('o_attachmentnumber_', '') + '"]');
            if (tmp1 != o.attr('type')) {
                if (tmp1 != '') tmp += '</dl>';
                tmp1 = o.attr('type');
                tmp += '<dl><dt>' + tmp1 + '</dt>';
            }
            tmp += '<dd class="title">' + o.attr('name') + '</dd><dd>' + s + o.attr('units') + '×&yen;' + (price < 0 ? price * -1 : price) + '<em class="price">' + (c < 0 ? '-&yen;' + (c * -1) : '&yen;' + c) + '</em></dd>';
        }
    });
    if (tmp1 != '') tmp += '</dl>';
    tmp1 = '';
    if (count[0] < 0) count[0] = 0;
    $('#TourExForm :submit').attr('disabled', count[3] == 0);
    if (count[2] > count[0]) count[2] = count[0];
    $('#kyjj').html(count[2] + webconfig().bonusunits);
    var dj = 0; //订金
	if(count[3]>0){
		if ($("#paytype").val() == "0") {
		    dj = Math.round(count[0] * toInt($('#deposit').val()) / 100);
		} else {
		    dj = (count[3] * toInt($('#deposit').val()));
			if (dj > count[0]) dj = count[0];
		}
	}
    var qt1 = count[0] - dj; //前台支付金额
    //使用奖金
    var re = count[0]; //要支付的金额
    switch (webconfig().promotionreckon) {
        case 0:
            obj = bonuscompute(re, count[2]);
            dj -= obj[0];
            if (dj < 0) {
                qt1 += dj;
                dj = 0;
            }
            tmp += obj[1];
            re = qt1 + dj;
            obj = promotioncompute(re, count[3]);
            dj -= obj[0];
            if (dj < 0) {
                qt1 += dj;
                dj = 0;
            }
            tmp += obj[1];
            re = qt1 + dj;
            break;
        case 1:
            obj = promotioncompute(re, count[3]);
            dj -= obj[0];
            if (dj < 0) {
                qt1 += dj;
                dj = 0;
            }
            tmp += obj[1];
            re = qt1 + dj;
            obj = bonuscompute(re, count[2]);
            dj -= obj[0];
            if (dj < 0) {
                qt1 += dj;
                dj = 0;
            }
            tmp += obj[1];
            re = qt1 + dj;
            break;
        default:
            obj = bonuscompute(re, count[2]);
            dj -= obj[0];
            if (dj < 0) {
                qt1 += dj;
                dj = 0;
            }
            re = qt1 + dj;
            if (obj[1] == '') {
                obj = promotioncompute(re, count[3]);
                dj -= obj[0];
                if (dj < 0) {
                    qt1 += dj;
                    dj = 0;
                }
                re = qt1 + dj;
            }
            tmp += obj[1];
            re = qt1 + dj;
            break;
    }

    var v1 = 0; //计算代金卷
    $('#xjcard input[name^="card_"]').each(function () {
        var v = toInt($(this).val());
        if (v > 0) {
            if (v + v1 > re) {
                v = re - v1;
            }
            v1 += v;
        } else {
            v = 0;
        }
        $(this).val(v);
    });
    dj -= v1;
    if (dj < 0) {
        qt1 += dj;
        dj = 0;
    }
    if (v1 > 0) tmp += '<dl><dd>使用代金卷<em class="price">-&yen;' + v1 + '</em></dd></dl>';
    $('#Billinginfo>.detailedBox>.content>h1,#Billinginfo>.detailedBox>.content>dl').remove();
    $('#Billinginfo>.detailedBox>.content').prepend(tmp);
    $('#Billinginfos>.detailedBox>.content>h1,#Billinginfos>.detailedBox>.content>dl').remove();
    $('#Billinginfos>.detailedBox>.content').prepend(tmp);
    $('#o_feescount').html('&yen;' + count[0]);
    $('#o_feescount1s').html('&yen;' + count[0]);
    $('#o_feescounts').html('&yen;' + count[0]);
    $('#o_feescount2').html('&yen;' + count[0]);
    $('.total').width('auto').html('<li>前台支付</li><li><em class="price">&yen;' + qt1.toFixed(2) + '</em></li><li>在线支付</li><li><em class="price">&yen;' + dj.toFixed(2) + '</em></li>');
    $('#zx').html('&yen;' + dj.toFixed(2));
    $('#zxs').html('&yen;' + dj.toFixed(2));
    $('#qt').html('&yen;' + qt1.toFixed(2));
    $('#qts').html('&yen;' + qt1.toFixed(2));
}
function bonuscompute(c0, c2) {//费用总计,可使用奖金,返回[使用积分总数,明细字符]
    var v = 0, v1 = 0, tmp1 = '', c = 0;
    if (c0 == 0 || c2 == 0) {//未登录或不允许使用奖金
        $('#dyorcard input[name^="card_"]').val(0);
        return [0, ''];
    }
    if ($('#sydy').length == 1 && $('#sydy').prop('checked') == false) return [0, '']; //未选择使用奖金
    if (GetCookie('username') != '') 
    {
        v = toInt($('#o_diyong').val());
        if (v > 0) {
            if (v > c2) v = c2;
            if (v > 0) {
                c2 -= v;
                tmp1 = '<dd>使用' + webconfig().bonusname + '<em class="price">-&yen;' + v + '</em></dd>';
            } else {
                v = 0;
            }
        } else {
            v = 0;
        }
    }
    $('#o_diyong').val(v);
    c = v;
    $('#dyorcard input[name^="card_"]').each(function () {
        v = toInt($(this).val());
        if (v > 0) {
            if (v > c2) v = c2;
            if (v > 0) {
                c2 -= v;
                v1 += v;
            } else {
                v = 0;
            }
        } else {
            v = 0;
        }
        c += v;
        $(this).val(v);
    });
    if (v1 > 0) tmp1 += '<dd>使用卡卷<em class="price">-&yen;' + v1 + '</em></dd>';
    if (tmp1 != '') tmp1 = '<dl><dt>使用' + webconfig().bonusname + '或卡卷</dt>' + tmp1 + '</dl>';
    return [c, tmp1];
}
function promotioncompute(c0, c3) {//c0可优惠金额,c3数量,返回优惠金额
    if ($('#yxcl').length == 1) {
        if ($('#yxcl:checked').length == 0) return [0, ''];
    }
    var name, s1, s2, obj, v, tmp1 = '', c = 0, r, cardcount;
    $('#Promotion [name="O_PromotionID"]').each(function () {
        obj = $(this);
        name = obj.parent().parent().text();
        obj.attr('disabled', true);
        s1 = toInt(obj.attr('minimum'));
        s2 = toInt(obj.attr('discountvalue'));
        r = toInt(obj.attr('circle'));
        cardcount = toInt(obj.attr('cardcount'));
        switch (obj.attr('ruletype')) {
            case '0':
                if (s1 <= c3) {
                    obj.attr('disabled', false);
                    if (obj.filter(':checked').length == 1) {
                        if (obj.attr('discounttype') == '0') {
                            v = Math.round(c0 * s2 / 100);
                        } else {
                            v = (r == 1 ? s2 * toInt(c3 / s1) : s2);
                        }
                        if (v > c0) v = c0;
                        c = v;
                        if (v > 0) tmp1 = '<dl><dt>优惠方案</dt><dd>' + name + '<em class="price">-&yen;' + v + '</em></dd></dl>';
                    }
                } else {
                    obj.prop('checked', false);
                }
                break;
            case '1':
                if (s1 <= c0) {
                    obj.attr('disabled', false);
                    if (obj.filter(':checked').length == 1) {
                        if (obj.attr('discounttype') == '0') {
                            v = Math.round(c0 * s2 / 100);
                        } else {
                            v = (r == 1 ? s2 * toInt(c0 / s1) : s2);
                        }
                        if (v > c0) v = c0;
                        c = v;
                        if (v > 0) tmp1 = '<dl><dt>优惠方案</dt><dd>' + name + '<em class="price">-&yen;' + v + '</em></dd></dl>';
                    }
                } else {
                    obj.prop('checked', false);
                }
                break;
            case '2':
                if (s1 <= c0) {
                    obj.attr('disabled', false);
                    if (obj.filter(':checked').length == 1) {
                        if (obj.attr('discounttype') == '0') {
                            v = Math.round(c0 * s2 / 100);
                        } else {
                            v = (r == 1 ? s2 * toInt(c0 / s1) : s2);
                        }
                        if (v > c0) v = c0;
                        c = v;
                        if (v > 0) tmp1 = '<dl><dt>优惠方案</dt><dd>' + name + '<em class="price">-&yen;' + v + '</em></dd></dl>';
                    }
                } else {
                    obj.prop('checked', false);
                }
                break;
            case '3':
                if (s1 <= c3) {
                    obj.attr('disabled', false);
                    if (obj.filter(':checked').length == 1) {
                        var s = (r == 1 ? toInt(c3 / s1) : 1);
                        if (cardcount < s) s = cardcount;
                        tmp1 = '<dl><dt>优惠方案</dt><dd>' + name + '<em class="price">' + s + '张</em></dd></dl>';
                    }
                } else {
                    obj.prop('checked', false);
                }
                break;
            case '4':
                if (s1 <= c0) {
                    obj.attr('disabled', false);
                    if (obj.filter(':checked').length == 1) {
                        var s = (r == 1 ? toInt(c0 / s1) : 1);
                        if (cardcount < s) s = cardcount;
                        tmp1 = '<dl><dt>优惠方案</dt><dd>' + name + '<em class="price">' + s + '张</em></dd></dl>';
                    }
                } else {
                    obj.prop('checked', false);
                }
                break;
            default:
                if (s1 <= c0) {
                    obj.attr('disabled', false);
                    if (obj.filter(':checked').length == 1) {
                        var s = (r == 1 ? toInt(c0 / s1) : 1);
                        if (cardcount < s) s = cardcount;
                        tmp1 = '<dl><dt>优惠方案</dt><dd>' + name + '<em class="price">' + s + '张</em></dd></dl>';
                    }
                } else {
                    obj.prop('checked', false);
                }
                break;
        }
    });
    return [c, tmp1];
}
var tempUserGC;
function LoadUserContact(gid, domId) {
    if (tempUserGC == null) return;
    $('#menu_' + domId).hide();
    var selectGC;
    for (var i = 0; i < tempUserGC.length; i++) {
        if (tempUserGC[i].UC_ID == gid) {
            selectGC = tempUserGC[i]
        }
    }
    $('#' + domId).val(selectGC.UC_RealName);
    $('#' + domId.replace("name", "card")).val(selectGC.UC_CardId);
    $('#' + domId.replace("name", "mobile")).val(selectGC.UC_Mobile);
    $("input[name='" + domId.replace("name", "sex") + "'][value='" + selectGC.UC_Sex + "']").prop("checked", true);
}
